const fs = require('fs')
const path = require('path')
const SparkMD5 = require('spark-md5')
const { R } = require('../utils')
const config = require('../config/index')

const delay = (time = 500) => {
  return new Promise((reslove) => {
    setTimeout(() => {
      reslove()
    }, time);
  })
}

const sleep = async (ctx, next) => {
  await delay()
  await next()
}

const rf = (path) => {
  return new Promise((reslove, reject) => {
    fs.readFile(path, (err, data) => {
      if (err) {
        reject()
      } else {
        reslove(data)
      }
    })
  })
}

const wf = (path, bf) => {
  return new Promise((reslove, reject) => {
    fs.writeFile(path, bf, (err) => {
      if (err) {
        reject()
      } else {
        reslove()
      }
    })
  })
}

const readFlieOfBlod = async (ctx, next) => {
  const { file } = ctx.request.files
  const fileBuffer = await rf(file.filepath)
  const spark = new SparkMD5()
  spark.append(fileBuffer)
  const hashname = spark.end()
  const extname = path.extname(file.filepath)
  const exists = fs.existsSync(path.resolve(__dirname, '../static', `${hashname}${extname}`))
  ctx.request.exists = exists
  ctx.request.filename = `${hashname}${extname}`
  ctx.request.fileBuffer = fileBuffer
  await next()
}

const readFlieOfSplit = async (ctx, next) => {
  const { file } = ctx.request.files
  const { filename, sufixname, dirname } = ctx.request.headers
  const dir = path.resolve(__dirname, '../static', dirname)
  const isExistsDir = fs.existsSync(dir)
  if (isExistsDir) {
    const isExistsFile = fs.existsSync(path.resolve(__dirname, '../static', dirname, filename))
    if (isExistsFile) {
      ctx.body = R.success(
        {
          path: '',
          type: 0
        },
        '上传成功'
      )
    } else {
      const bf = await rf(file.filepath)
      await wf(path.resolve(dir, `${filename}.${sufixname}`), bf)
      ctx.body = R.success(
        {
          path: '',
          type: 1
        },
        '上传成功'
      )
    }
  } else {
    try {
      fs.mkdirSync(dir)
      const bf = await rf(file.filepath)
      await wf(path.resolve(dir, `${filename}.${sufixname}`), bf)
      ctx.body = R.success(
        {
          path: '',
          type: 1
        },
        '上传成功'
      )
    } catch (error) {
      ctx.body = R.error(500, "写入失败" + error)
    }
  }
}

const mergeFile = async (ctx, next) => {
  const { filename, sufixname } = ctx.request.query
  if (!filename || !sufixname) {
    ctx.body = R.error(400, '参数有误')
    return
  }
  const dir = path.resolve(__dirname, '../static', filename)
  const exists = fs.existsSync(dir)
  if (!exists) {
    ctx.body = R.error(400, '文件不存在')
    return
  }
  const fileList = fs.readdirSync(dir)
  fileList.forEach(file => {
    const buf = fs.readFileSync(path.resolve(dir, file))
    fs.appendFileSync(path.resolve(__dirname, '../static', `${filename}.${sufixname}`), buf)
  })
  fs.rmSync(dir, { recursive:true })
  ctx.body = R.success(
    {
      path: `1`,
      type: 0
    },
    '上传成功'
  )
}

const writeFile = async (ctx, next) => {
  const { exists, filename, fileBuffer } = ctx.request
  if (exists) {
    ctx.body = R.success(
      {
        path: `${config.APP_HOST}:${config.APP_PROT}/${filename}`,
        type: 0
      },
      '上传成功'
    )
  } else {
    try {
      await wf(path.resolve(__dirname, '../static', `${filename}`), fileBuffer)
      ctx.body = R.success(
        {
          path: `${config.APP_HOST}:${config.APP_PROT}/${filename}`,
          type: 1
        },
        '上传成功'
      )
    } catch (error) {
      ctx.body = R.error(500, '上传失败')
    }
  }
}

const readFlieOfBase = async (ctx, next) => {
  const body = ctx.request.body
  console.log(body);
  await next()
}

module.exports = {
  readFlieOfBlod,
  readFlieOfSplit,
  mergeFile,
  readFlieOfBase,
  writeFile,
  sleep
}